<? { ?>
	<style type="text/css">
		#result table tr th {
			background: url(templates/builder/images/slate/grid/grid3-hrow.gif) repeat-x; 
			border-left: 1px solid #eee;
			border-right: 1px solid #d0d0d0;
			font-size: 11px;
			padding: 5px;
		}
		#result table tr td {
			background-color: #ddd;
			padding: 5px;
			font-size: 11px;
		}
		#result table tr.grey td {
			background-color: #ccc;
		}
		#result table tr:hover td {
			background-color: #ffffcc;
		}
		#result table tr.selected td {
			background-color: #ffffaa;
		}
	</style>
	<div style="padding:20px;">
	<div style="float:left;width:49%;position:relative;">
		SQL Editor
		<div id="query_container" data-bespinoptions='{"syntax": "sql"}' style="height:54px;padding:2px 3px;border:1px solid #9ab;"></div>
	</div>
	<div style="float:left;margin-left:1%;width:49%;position:relative;">
		Scratch Pad
		<div id="clip_container"></div>
	</div>
	<div style="clear:both;margin-bottom:3px;"></div>
	<div id="result_container" style=""></div>
	<script type="text/javascript">
		(function(){
			
			window.initTableList = function() {
				$$("#result tr td").each(function(item){
					item.observe("click", function(event){
						if (!this.up().down("td", 1)) return false;
						var tbl = this.up().down("td", 1).innerHTML.stripTags().strip();
						window.runQuery("SELECT * FROM tbl_"+tbl+" WHERE 1=1", true);
						event.stop();
					}.bindAsEventListener(item));
				});				
			};
							
			window.runQuery = function(query, callback, hide) {
				if ((query || Builder.getCode("query_container")).strip().length <= 0) return false;

				var shortQuery = (query || Builder.getCode("query_container"));
				if (shortQuery.length > 50) shortQuery = shortQuery.substr(0, 50);

				invoke(null, "builder:queryTest&check=1", {
					"query": query || Builder.getCode("query_container")
				}, true, function(req) {
					try {
						$("result_container").update("");
					var fields = [];
					var cols = [];
					var data = eval("("+req.responseText+")");
					
					for (var each in data["result"][0]) {
						if (typeof(data.result[0][each]) != "function" && typeof(data.result[0][each])) {
							fields.push(each);
							if (each != "id") {
								cols.push({header: each, dataIndex: each, sortable: !hide, editor: new Ext.form.TextField()});
							} else {
								cols.push({header: each, dataIndex: each});
							}
						}
					}
					var store = new Ext.data.JsonStore({
						url: "?event=builder:queryTest&check=2&total="+data['total']+"&query="+data["query"],
						autoDestroy: true,
						storeId: "queryStore",
						root: "result",
						remoteSort: true,
						totalProperty: "total",
						idProperty: "id",
						fields: fields
					});
					
					var grid = new (hide ? Ext.grid.GridPanel : Ext.grid.EditorGridPanel)({
						id: "resultGrid",
						layout: "fit",
				        loadMask: true,						
						height: $("result_container").up().up().getHeight() - $("result_container").offsetTop - 40,
						autoScroll: true,						
						store: store,
						title: (hide ? "Table List" : "Query Result for: "+shortQuery),
						renderTo: "result_container",
					    sm: new Ext.grid.RowSelectionModel({
					    	singleSelect:false,
					        listeners: {
					        	rowselect: function(e, d, g) {
					        		if (hide) {
					        			window.currentQueryTable = g.data["table_name"].replace(/<[^>]+>/gi, '');
										window.runQuery("SELECT * FROM tbl_"+window.currentQueryTable+" WHERE 1=1", true);
					        		}
					        	}
					        }
					    }),
					    colModel: new Ext.grid.ColumnModel({
					        defaults: {sortable: true},
					        columns: cols
					    }),
					    tbar: [{
					    	xtype: "button",
					    	text: "Save Changes",
					    	iconCls: "save",
					    	disabled: hide,
					    	handler: function() {
								var recs = Ext.getCmp("resultGrid").getStore().getModifiedRecords();
								if (recs.length <= 0) {
									Ext.Msg.alert("Saving", "Nothing to be saved. No records were modified.");
									return;
								}
								window.committing = recs.length;
								for (var i = 0; i < recs.length; i++) {
									rec = recs[i];
									cqtid = window.currentQueryTable.replace(/_key$/gi, '') + "_id";
									var id = rec.data[cqtid];
									var c = rec.getChanges();
									var set = "";
									for (var each in c) {
										if (set.length > 0) set += ", ";
										set += each + "='"+c[each].replace("'", "''")+"'";
									} 
									var query = "UPDATE tbl_"+window.currentQueryTable+" SET "+set+" WHERE "+cqtid+"="+id+"";
									invoke(null, "builder:queryTest&check=1", {
										"query": query
									}, true, function() {
										rec.commit();
										window.committing--;
									});
								}
								new PeriodicalExecuter(function(pe){
									if (window.committing <= 0) {
										pe.stop();
				            			window.runQuery("SELECT * FROM tbl_"+window.currentQueryTable+" WHERE 1=1");								
									}
								}, 0.1);
					    	}
					   	}, "-", {
			            	xtype: "button",
			            	text: "Add Row",
			            	iconCls: "add",
			            	disabled: hide,
			            	handler: function() {
			            		<? if (DB_TYPE == SQLITE) { ?>
			            			var addQuery = "INSERT INTO tbl_"+window.currentQueryTable+" DEFAULT VALUES";
			            		<? } else { ?>
			            			var addQuery = "INSERT INTO tbl_"+window.currentQueryTable+" () VALUES ()";
			            		<? } ?>
								invoke(null, "builder:queryTest&check=1", {
									"query": addQuery
								}, true, function(req) {
			            			window.runQuery("SELECT * FROM tbl_"+window.currentQueryTable+" WHERE 1=1");
			            		});
			            	}
			            }, {
			            	xtype: "button",
			            	text: "Delete Row",
			            	iconCls: "delete",
			            	disabled: hide,
			            	handler: function() {
			            		rec = Ext.getCmp("resultGrid").getSelectionModel().getSelections();
			            		if (rec) {
			            			var vars = "";
									cqtid = window.currentQueryTable.replace(/_key$/gi, '') + "_id";			            				
			            			for (var i = 0; i < rec.length; i++) {
			            				if (vars.length > 0) vars += ",";
			            				vars += rec[i].data[cqtid];
			            			}
				            		var cond = cqtid+" IN ("+vars+")";
									invoke(null, "builder:queryTest&check=1", {
										"query": "DELETE FROM tbl_"+window.currentQueryTable+" WHERE "+cond
									}, true, function() {
										setTimeout(function() {
				            				window.runQuery("SELECT * FROM tbl_"+window.currentQueryTable+" WHERE 1=1");
										}, 100);
				            		});
			            		}
			            	}
			            }, "-", "Search:", " ", new Ext.ux.form.SearchField({
			                store: store,
			                width:150
			            })],
						bbar: pb = new Ext.PagingToolbar({
				            pageSize: 25,
				            store: store,
				            displayInfo: true,
				            displayMsg: 'Displaying results {0} - {1} of {2}',
				            emptyMsg: "No results to display"
				        })
					});	
				
					grid.store.on('load',grid.autoSizeColumns,grid);
					grid.on('afteredit', function(e) {
//						if (e.field) 
					});
					store.load({params: {start: 0, limit: 25}});

					if (typeof(callback) == "function") {
						new PeriodicalExecuter(function(pe) {
							callback();
							pe.stop();
						}, 0.5);
					}
					} catch(e) {alert(e.message);}
				});				
			};
			
			new Ext.form.TextArea({
				grow: true,
				fieldLabel: "Clipboard",
				width: "100%",
				renderTo: "clip_container",
				anchor:'95%'
			});
			Ext.getCmp("portlet_content_query_test").getTopToolbar().add([{
				xtype: "button",
				text: "Execute Query",
				iconCls: "run",
				tooltip: "Ctrl+Shift+X",
				handler: function(e){
					window.runQuery();
				}
			},{
				xtype: "button",
				text: "Overview",
				iconCls: "table",
				handler: function(e) {
					window.runQuery("SELECT name AS table_name, REPLACE(field_names, ':', ', ') AS fields FROM tbl_prailsbase_table WHERE fk_user_id=\"<?=$_SESSION['builder']['user_id']?>\"", window.initTableList, true);
				}
			}]);
			Ext.getCmp("portlet_content_query_test").getTopToolbar().doLayout();
			Ext.QuickTips.init();
			Builder.applyBespin($("query_container"));
			new PeriodicalExecuter(function(pe) {
				pe.stop();
/*
				if (window.sqlQuery.editor != null) {
					window.sqlQuery.editor.doc.parent = window;
					window.sqlQuery.editor.doc.run = function(){
						window.runQuery();
					};
				}//*/
				window.runQuery("SELECT name AS table_name, REPLACE(field_names, ':', ', ') AS fields FROM tbl_prailsbase_table WHERE fk_user_id=\"<?=$_SESSION['builder']['user_id']?>\"", window.initTableList, true);
			}, 0.5);
			
			Ext.override(Ext.CompositeElement, {
			    getTextWidth: function() {
			        var i, e, els = this.elements, result = 0;
			        for(i = 0; e = Ext.get(els[i]); i++) {
			            result = Math.max(result, e.getTextWidth.apply(e, arguments));
			        }
			        return result;
			    }
			});

			Ext.override(Ext.grid.GridPanel, {
			    autoSizeColumns: function() {
			        this.colModel.suspendEvents();
			        for (var i = 0; i < this.colModel.getColumnCount(); i++) {
			            this.autoSizeColumn(i);
			        }
			        this.colModel.resumeEvents();
			        this.view.refresh(true);
			    },

			    autoSizeColumn: function(c) {
			        var col = this.view.el.select("td.x-grid3-td-" + this.colModel.getColumnId(c) + " div:first-child");
			        if (col) {
			        	 	var i, e, els = col.elements, result = 0;
					        for(i = 0; e = Ext.get(els[i]); i++) {
					            result = Math.max(result, e.getTextWidth.apply(e, []));
					        }
					        gtw = result;
					        
			            var w = gtw + Ext.get(col.elements[0]).getFrameWidth('lr') + 2;
			            this.colModel.setColumnWidth(c, w);
			            return w;
			        }
			    }
			});
		})();
	</script></div>
<? } ?>